package routers

import (
	"WebSvr/controllers"

	"WebSvr/modules/common"
	"WebSvr/modules/mysql"

	"WebSvr/modules/memList"

	"path/filepath"

	"fmt"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

const timeFormat string = "2006-01-02 15:04:05"
const logName string = ".log"
const logDir string = "/syslog"

func checkFileIsExist(filename string) bool {
	var exist = true
	_, err := os.Stat(filename)
	if err != nil {
		exist = false
	}
	return exist
}

func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		beego.Error(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func getFilePath() string {
	logPath := GetCurrentDirectory() + logDir
	err := os.MkdirAll(logPath, 0777)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("MkdirAll ok!")
	}

	timeStr := time.Now().Format(timeFormat)
	var timeSlice []string = strings.Split(timeStr, " ")
	var smhSlice []string = strings.Split(timeSlice[1], ":")
	fileName := timeSlice[0] + " " + smhSlice[0] + smhSlice[1] + smhSlice[2] + logName
	var fullPath string = logPath + "/" + fileName
	return fullPath
}

func initLog() {
	//log
	fullPath := getFilePath()
	bExist := checkFileIsExist(fullPath)
	if !bExist {
		_, fileErr := os.Create(fullPath)
		if fileErr != nil {
			beego.Error(fileErr)
			return
		}
	}

	logStr := fmt.Sprintf(`{"filename":"%s"}`, fullPath)
	beego.SetLogger("file", logStr)
	beego.SetLevel(beego.LevelInformational)
}

func init() {
	initLog()
	mysql.Initmysql()
	cycle := beego.AppConfig.String("checkCycle")
	maxAfford := beego.AppConfig.String("maxafford")

	getRunMode()
	str := fmt.Sprintf("runmode:%d", common.DebugCtrl)
	beego.Info(str)
	cycle_int64, _ := strconv.ParseInt(cycle, 10, 64)

	if cycle_int64 <= 0 {
		beego.Error("配置的定时循环checkCycle小于等于0")
		panic("配置的定时循环checkCycle小于等于0")
		return
	}
	maxAfford_int64, _ := strconv.ParseInt(maxAfford, 10, 64)
	memList.NewMemListMgr(cycle_int64, maxAfford_int64)
	memListMgr := memList.GetMemListMgr()
	memList.NewTokenMgr()
	//开协程定时
	go memListMgr.OnTimer()

	initRouter()
}

func initRouter() {
	//handle login
	beego.Router("/", &controllers.LoginController{}, "get:Get")
	beego.Router("/adminLogin", &controllers.LoginController{}, "post:PostAdminLogin")
	beego.Router("/logOut", &controllers.LoginController{}, "get:GetLogOut")
	beego.Router("/loginAccess", &controllers.LoginController{}, "get:GetAccessByip")
	//handle ServerCfg
	beego.Router("/adminHome", &controllers.WebServerCfgController{}, "get:GetAdminHome")
	beego.Router("/admingetServerData", &controllers.WebServerCfgController{}, "get:GetAllServerDataByAdmin")
	beego.Router("/c2sSave", &controllers.WebServerCfgController{}, "post:PostSaveServerCfg")
	beego.Router("/c2sDel", &controllers.WebServerCfgController{}, "post:PostDelServerCfg")
	//handle UserCfg
	beego.Router("/adminUser", &controllers.WebUserCfgController{}, "get:GetAdminUser")
	beego.Router("/admingetUser", &controllers.WebUserCfgController{}, "get:GetUserData")
	beego.Router("/c2sSaveUser", &controllers.WebUserCfgController{}, "post:PostSaveUserCfg")
	beego.Router("/c2sDelUser", &controllers.WebUserCfgController{}, "post:PostDelUserCfg")
	//handle Echart
	beego.Router("/reportWeb", &controllers.ReportController{}, "get:GetreportWeb")
	beego.Router("/getServerName", &controllers.ReportController{}, "get:GetServerName")
	beego.Router("/getPcInfo", &controllers.ReportController{}, "get:GetPcInfo")
	//handle Announce
	beego.Router("/announce", &controllers.AnnounceController{}, "get:GetAnnounceTab")
	beego.Router("/sendAnnounceText", &controllers.AnnounceController{}, "post:PostSendAnnounceText")
	beego.Router("/getAnnounce", &controllers.AnnounceController{}, "get:GetAnnounceContent")
	//handle serverlist
	beego.Router("/getServerList", &controllers.ServerListController{}, "get:GetServerList")
	beego.Router("/onlineReport", &controllers.ServerListController{}, "post:PostOnlineReport")
	beego.Router("/sysReport", &controllers.ServerListController{}, "post:PostSysReport")

}
